package com.bifrost.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.bifrost.annotation.Authorization;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.annotation.CurrentUser;
import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.entity.*;
import com.bifrost.common.model.ResultModel;
import com.bifrost.model.review.ReviewRequest;
import com.bifrost.repository.ProductReviewRepository;
import com.bifrost.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author rangjf
 * @date 2017/10/31
 */
@Api("车品商城相关接口")
@RestController
@RequestMapping("/api/mall")
public class MallController {

    @Autowired
    MallService mallService;
    @Autowired
    ProductReviewService reviewService;
    @Autowired
    ProductSkuService skuService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;
    @Autowired
    CustomerService customerService;
    @Autowired
    StoreService storeService;
    @Autowired
    ProductReviewRepository reviewRepository;
    private static final Logger logger = LoggerFactory.getLogger(MallController.class);

    @ApiOperation("获取商品类别")
    @ApiImplicitParam(paramType = "query", name = "parentId", value = "类别父id", required = false, dataType = "Long")
    @PostMapping("/category")
    public ResultModel getCategories(@CurrentStore Long storeId, Long parentId) {
        if(null == storeId){
            return ResultModel.error("没有数据");
        }
        List<Map> categories = mallService.getCategories(storeId,parentId);
        /*MerchantStore store = storeService.getMerchantStore(storeId);
        List<Category> categoryList = mallService.getCategories(store, parentId);
        if (CollectionUtils.isEmpty(categoryList)) {
            return ResultModel.error("没有数据");
        }
        List<Map> categories = new ArrayList<>();
        categoryList.forEach(category -> {
            Map map = new HashMap(3);
            map.put("categoryId", category.getCategoryId());
            Media media = category.getMedia();
            map.put("imgUrl", media == null ? "" : HttpRequestUtils.getUrl(media.getUrl()));
            map.put("categoryName", category.getCategoryName());
            Boolean isVisiable = category.getIsVisible();
            if (isVisiable != null && isVisiable) {
                categories.add(map);
            }
        });*/
        if (parentId != null) {
            Category category = categoryService.findById(parentId);
            Media media = category.getMedia();
            return ResultModel.ok()
                    .put("id", category.getCategoryId())
                    .put("name", category.getCategoryName())
                    .put("url", media == null ? "" : HttpRequestUtils.getUrl(media.getUrl()))
                    .put("categories", categories);
        } else {
            return ResultModel.ok()
                    .put("categories", categories);
        }
    }

    @ApiOperation("按类别获取商品/商品筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "categoryId", value = "类别Id", required = false, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "sortType", value = "排序方式:【0综合,1价格↑,2价格↓,3销量↓】", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "minPrice", value = "最低价", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "maxPrice", value = "最高价", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "queryKey", value = "搜索关键字", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "brandIds", value = "品牌筛选Id字符串【英文逗号分隔】", required = false, dataType = "String")
    })
    @PostMapping("/products")
    public ResultModel getProducts(@CurrentStore Long storeId, Long categoryId, @RequestParam(value = "page", defaultValue = "1") String page,
                                   @RequestParam(value = "pageSize", defaultValue = "10") String pageSize, String sortType,
                                   String minPrice, String maxPrice, String queryKey, String brandIds) {
        Category category = null;
        if(categoryId != null){
            category = categoryService.findById(categoryId);
        }
        Page<ProductSku> data = null;
        if (storeId!=null) {
            MerchantStore store = storeService.getMerchantStore(storeId);
            data= mallService.getProductsByStore(store,category, Integer.parseInt(page), Integer.parseInt(pageSize), sortType, minPrice, maxPrice, queryKey, brandIds);
        }else {
            data= mallService.getProducts(category, Integer.parseInt(page), Integer.parseInt(pageSize), sortType, minPrice, maxPrice, queryKey, brandIds);
        }
        if (data != null && data.hasContent()) {
            List<ProductSku> skuList = data.getContent();
            if (CollectionUtils.isNotEmpty(skuList)) {
                skuList = skuList.stream().map(sku -> {return sku.getProduct().getDefaultSku();}).distinct().collect(Collectors.toList());
                List<Map> skus = new ArrayList<>();
                for (ProductSku productSku : skuList) {
                    Product product = productSku.getProduct();
                    if(Boolean.TRUE.equals(product.isArchived()) || Boolean.FALSE.equals(product.isAvailable())){ continue; }
                    skuService.pricingBundleProduct(productSku);
                    Map map = new HashMap(14);
                    map.put("skuId", productSku.getSkuId());
                    map.put("skuName", productSku.getSkuName());
                    map.put("salePrices", productSku.getSalePrice());
                    map.put("retailPrices", productSku.getRetailPrice());
                    map.put("salesCount", productSku.getSaleCount());
                    Integer reviewCount = reviewRepository.countFinalSkuReview(productSku);
                    map.put("reviewCount", reviewCount==null?0:reviewCount);
                    map.put("skuDesc", productSku.getSkuDescription());
                    Media media = skuService.getSkuDefaultMedia(productSku.isDefault()?productSku:product.getDefaultSku());
                    map.put("url", media == null ? null : HttpRequestUtils.getUrl(media.getUrl()));
                    Integer inventory = inventoryService.retrieveQuantityAvailable(productSku.getProduct());
                    map.put("isAvalible", true);
                    if (inventory==null||inventory<=0) {
                        map.put("isAvalible", false);
                        map.put("unAvalibleReson", "库存不足");
                    }
                    map.put("canAddCart", !Boolean.FALSE.equals(productSku.getCanAddCart()));
                    map.put("shippingType", productSku.getFulfillmentType());
                    map.put("skuAssociation", skuService.getSkuGiftAndService(productSku));
                    skus.add(map);
                }
                return ResultModel.ok()
                        .put("total", data.getTotalElements())
                        .put("page", data.getNumber())
                        .put("pageSize", data.getSize())
                        .put("totalPages", data.getTotalPages())
                        .put("skus", skus)
                        .put("categoryId", categoryId);
            }
        }
        return ResultModel.error("没有数据");
    }

    @ApiOperation("获取商品详细")
    @ApiImplicitParam(paramType = "query", name = "skuId", value = "商品", required = true, dataType = "Long")
    @GetMapping("/productDetail")
    public ResultModel getProductDetail(@RequestParam Long skuId) {
        Map map = mallService.getProductDetail(skuId);
        return ResultModel.ok(map);
    }
    @ApiOperation("获取商品详细")
    @ApiImplicitParam(paramType = "query", name = "skuId", value = "商品", required = true, dataType = "Long")
    @GetMapping("/skuDetail")
    public ResultModel getDetail(@RequestParam Long skuId) {
        Map map = mallService.getDetail(skuId);
        return ResultModel.ok(map);
    }
    @Authorization
    @ApiOperation("发布商品评论")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orderId", value = "订单Id", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "reviewModelList", value = "reviewModelList", required = true, dataType = "String")
    })
    @PostMapping("/reviewAdd")
    public ResultModel reviewAdd(@CurrentUser Long  userId, Long orderId, String data) {
        List<ReviewRequest> reviews = new ArrayList<>();
        reviews = JSONObject.parseArray(data, ReviewRequest.class);
        Customer customer = customerService.findCustomer(userId);
        return reviewService.addReview(customer, orderId, reviews, true);
    }

    @ApiOperation("获取商品所有评论")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "skuId", value = "skuId", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "flag", value = "有图评价【1有图,0无图】", required = false, dataType = "String")
    })
    @GetMapping("/reviews")
    public ResultModel getProductReviews(@RequestParam Long skuId, @RequestParam(value = "page", defaultValue = "1") String page,
                                         @RequestParam(value = "pageSize", defaultValue = "10") String pageSize, String flag) {
        Map map = reviewService.getReviews(skuId, Integer.parseInt(page), Integer.parseInt(pageSize), flag);
        return ResultModel.ok(map);
    }

    @ApiOperation("获取商品图文描述")
    @ApiImplicitParam(paramType = "query", name = "skuId", value = "skuId", required = true, dataType = "Long")
    @GetMapping("/productDesc")
    public ResultModel getProductDesc(@RequestParam Long skuId) {
        return ResultModel.ok().put("images", mallService.getProductDesc(skuId));
    }

    @ApiOperation("获取热销推荐商品")
    @GetMapping("/hot/products")
    @ApiImplicitParam
    public ResultModel getHotProducts(@CurrentStore Long storeId, String queryKey, String brandIds,
                                      @RequestParam(value = "page", defaultValue = "1")Integer page,
                                      @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize) {
        MerchantStore store = storeService.getMerchantStore(storeId);
        return mallService.getHotProducts(store, queryKey, brandIds, page, pageSize);
    }
    @ApiOperation("获取热销推荐商品")
    @GetMapping("/hot/productsById")
    @ApiImplicitParam
    public ResultModel getHotProductsById(String merchantId ,String queryKey, String brandIds, @RequestParam(value = "page", defaultValue = "1")Integer page, @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize){

         MerchantStore merchantStore = storeService.getMerchantStore(Long.parseLong(merchantId));

        return mallService.getHotProducts(merchantStore, queryKey, brandIds, page, pageSize);
    }


}
